package com.sanjin.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sanjin.mall.product.dao.BrandDao;
import com.sanjin.mall.product.entity.BrandEntity;
import com.sanjin.mall.product.entity.CategoryEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sanjin.mall.common.utils.PageUtils;
import com.sanjin.mall.common.utils.Query;

import com.sanjin.mall.product.dao.CategoryBrandRelationDao;
import com.sanjin.mall.product.entity.CategoryBrandRelationEntity;
import com.sanjin.mall.product.service.CategoryBrandRelationService;


@Service("categoryBrandRelationService")
public class CategoryBrandRelationServiceImpl extends ServiceImpl<CategoryBrandRelationDao, CategoryBrandRelationEntity> implements CategoryBrandRelationService {

    @Autowired
    private BrandDao brandDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryBrandRelationEntity> page = this.page(
                new Query<CategoryBrandRelationEntity>().getPage(params),
                new QueryWrapper<CategoryBrandRelationEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 级联更新
     * @param brandEntity
     */
    @Override
    public void updateBrandNameById(BrandEntity brandEntity) {
        Long brandId = brandEntity.getBrandId();
        String name = brandEntity.getName();
        CategoryBrandRelationEntity dao = new CategoryBrandRelationEntity();
        dao.setBrandName(name);
        dao.setBrandId(brandId);
        baseMapper.update(dao, new UpdateWrapper<CategoryBrandRelationEntity>().eq("brand_id", brandId));

    }

    @Override
    public void updateCatelogNameById(CategoryEntity category) {
        Long catId = category.getCatId();
        String name = category.getName();
        CategoryBrandRelationEntity dao = new CategoryBrandRelationEntity();
        dao.setCatelogId(catId);
        dao.setCatelogName(name);
        baseMapper.update(dao, new UpdateWrapper<CategoryBrandRelationEntity>().eq("catelog_id", catId));

    }

    @Override
    public List<BrandEntity> getBrandsByCatId(Long catId) {
        List<CategoryBrandRelationEntity> list = baseMapper.selectList(new QueryWrapper<CategoryBrandRelationEntity>().eq("catelog_id", catId));
        List<BrandEntity> brandEntityList = list.stream().map(x -> {
            Long brandId = x.getBrandId();
            return brandDao.selectById(brandId);
        }).collect(Collectors.toList());
        return brandEntityList;
    }


}